<?php

namespace App\Libs\Vm;

use AlibabaCloud\SDK\Ecs\V20140526\Ecs;
use AlibabaCloud\SDK\Ecs\V20140526\Models\DescribeInstanceAttributeRequest;
use AlibabaCloud\SDK\Ecs\V20140526\Models\DescribeInstancesRequest;
use AlibabaCloud\SDK\Ecs\V20140526\Models\DescribeRegionsRequest;
use AlibabaCloud\SDK\Ecs\V20140526\Models\RebootInstanceRequest;
use AlibabaCloud\SDK\Ecs\V20140526\Models\StartInstanceRequest;
use AlibabaCloud\SDK\Ecs\V20140526\Models\StopInstanceRequest;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;
use Exception;

class EcsLib
{
    /**
     * 使用AK&SK初始化账号Client
     * @return Ecs Client
     */
    public static function createClient($regionId){
        $config = new Config([
            "accessKeyId" => config("vm.alibaba_cloud_access_key_id"),
            "accessKeySecret" => config("vm.alibaba_cloud_access_key_secret")
        ]);
        $config->endpoint = 'ecs.'.$regionId.".aliyuncs.com";
        return new Ecs($config);
    }

    /**
     * Note - ECS实例属性信息
     * DateTime 2025/2/10 16:10
     * User Admin
     * @param $regionId
     * @param $instanceId
     * @return array
     */
    public static function info($regionId, $instanceId)
    {
        try {
            $client = self::createClient($regionId);
            $describeInstanceAttributeRequest = new DescribeInstanceAttributeRequest([
                "instanceId" => $instanceId
            ]);
            $runtime = new RuntimeOptions([]);
            // 复制代码运行请自行打印 API 的返回值
            $response = $client->describeInstanceAttributeWithOptions($describeInstanceAttributeRequest, $runtime);
            $data =  $response->body->toMap();
            return [
                'InstanceId' => $data['InstanceId'] ?? '',
                'Status' => strtolower($data['Status'] ?? '-'),
                'InstanceName' => $data['InstanceName'] ?? '',
                'Ip' => $data['PublicIpAddress']['IpAddress'][0] ?? ($data['EipAddress']['IpAddress'] ?? '')
            ];
        } catch (\Throwable $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            logInfo('ecs_info',['错误' => $error->getMessage(),'诊断地址' => $error->data["Recommend"] ?? 'url']);
            return [];
        }
    }

    /**
     * Note - ECS实例列表
     * DateTime 2025/2/6 10:37
     * User Admin
     */
    public static function list($regionId, $resourceGroupId){
        $client = self::createClient($regionId);
        $describeInstancesRequest = new DescribeInstancesRequest([
            "regionId" => $regionId,
            "resourceGroupId" => $resourceGroupId,
            'MaxResults' => 100
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $response = $client->describeInstancesWithOptions($describeInstancesRequest, $runtime);
            $data = $response->body->toMap();
            return $data["Instances"]["Instance"] ?? [];
        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // var_dump($error->message);
            // // 诊断地址
            // var_dump($error->data["Recommend"]);
            logInfo('ecs_list',['错误' => $error->getMessage(),'诊断地址' => $error->data["Recommend"] ?? 'url']);
            return [];
        }
    }

    /**
     * Note - ECS实例 启动
     * DateTime 2025/2/6 11:43
     * User Admin
     * @param $regionId
     * @param $instanceId
     * @return bool
     */
    public static function start($regionId,$instanceId){
        $client = self::createClient($regionId);
        $startInstanceRequest = new StartInstanceRequest([
            'instanceId' => $instanceId
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $response = $client->startInstanceWithOptions($startInstanceRequest, $runtime);
            $data = $response->body->toMap();
            logInfo('ecs_start',$data);
            if ($data["RequestId"]){
                return true;
            }
        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // var_dump($error->message);
            logInfo('ecs_start',['错误' => $error->getMessage(),'诊断地址' => $error->data["Recommend"] ?? 'url']);
        }
        return false;
    }

    /**
     * Note - ECS实例 重启
     * DateTime 2025/2/6 11:43
     * User Admin
     * @param $regionId
     * @param $instanceId
     * @return bool
     */
    public static function restart($regionId,$instanceId){
        $client = self::createClient($regionId);
        $rebootInstanceRequest = new RebootInstanceRequest([
            'instanceId' => $instanceId,
            'ForceStop' => true
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $response = $client->rebootInstanceWithOptions($rebootInstanceRequest, $runtime);
            $data = $response->body->toMap();
            if ($data["RequestId"]){
                return true;
            }
        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // // 错误 message
            // var_dump($error->message);
            // // 诊断地址
            // var_dump($error->data["Recommend"]);
            logInfo('ecs_restart',['错误' => $error->getMessage(),'诊断地址' => $error->data["Recommend"] ?? 'url']);
        }
        return false;
    }


    /**
     * Note - ECS实例 停机
     * DateTime 2025/2/6 11:43
     * User Admin
     * @param $regionId
     * @param $instanceId
     * @return bool
     */
    public static function shoutDown($regionId,$instanceId){
        $client = self::createClient($regionId);
        $stopInstanceRequest = new StopInstanceRequest([
            'stoppedMode' => 'StopCharging',// 停机节省模式；KeepCharging-保持计费状态；StopCharging-停机节省模式
            'instanceId' => $instanceId
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $response = $client->stopInstanceWithOptions($stopInstanceRequest, $runtime);
            $data = $response->body->toMap();
            if ($data["RequestId"]){
                return true;
            }
        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // // 错误 message
            // var_dump($error->message);
            // // 诊断地址
            // var_dump($error->data["Recommend"]);
            logInfo('ecs_shoutDown',['错误' => $error->getMessage(),'诊断地址' => $error->data["Recommend"] ?? 'url']);
        }
        return false;
    }

    public static function regionList()
    {
        $client = self::createClient('cn-hongkong');
        $describeRegionsRequest = new DescribeRegionsRequest([
            "instanceChargeType" => "PrePaid"
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $response = $client->describeRegionsWithOptions($describeRegionsRequest, $runtime);
            $data = $response->body->toMap();
            $list = [];
            foreach ($data["Regions"]["Region"] as $k =>$re) {
                $list[$k]['Region'] = $re["RegionId"];
                $list[$k]['RegionName'] = $re["LocalName"];
            }
            return $list;
        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            logInfo('shoutDown',['错误' => $error->getMessage(),'诊断地址' => $error->data["Recommend"] ?? 'url']);
        }
    }

}
